package com.vcredit.bird.service.identity;

import java.io.IOException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.vcredit.creditcat.exception.DataException;
import com.vcredit.creditcat.exception.IdAuthException;
import com.vcredit.creditcat.exception.RMCloudRequestException;
import com.vcredit.bird.service.base.RMC_BaseRespVo;
import com.vcredit.bird.service.base.RMCloudService;
import com.vcredit.bird.vo.identity.FacepairParam;
import com.vcredit.bird.vo.identity.OcrParam;
import com.vcredit.bird.vo.identity.YTBaseRes;
import com.vcredit.bird.vo.identity.YTFacePairResult;
import com.vcredit.bird.vo.identity.YTFacepairParam;
import com.vcredit.bird.vo.identity.YTOCRParam;
import com.vcredit.bird.vo.identity.YTOCRResult;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.JacksonUtil;

/**
 * 依图服务接口
 * 
 * @author
 *
 */
@Service
public class IdentityYituService extends RMCloudService {

	Logger logger = LoggerFactory.getLogger(IdentityYituService.class);

	@Value("${rmcloud.api.idcardocr}")
	private String yitu_idcardocr_url; // 依图身份证OCR解析
	@Value("${rmcloud.api.comparefacepair}")
	private String yitu_comparefacepair_url;// 依图活体人脸识别
	//活体识别相似度基线,达到70以上成功识别
	@Value("${similarity.baseline}")
	private int similarityBaseline;
	/**
	 * 调用依图OCR身份证信息解析 接口
	 * 
	 * @param param
	 * @return
	 * @throws VituException
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 * @throws RMCloudRequestException
	 * @throws DataException
	 */
	@Log
	public YTOCRResult idcardOcr(OcrParam ocrParam, String busType) throws IdAuthException, RMCloudRequestException {
		if (StringUtils.isBlank(ocrParam.getIdBase64())) {
			throw new IdAuthException("身份证图片未正确上传");
		}
		try {
			String param = JacksonUtil.Obj2Json(new YTOCRParam(ocrParam.getIdBase64(), busType));
			RMC_BaseRespVo rmcResp = super.postRMCloudData(yitu_idcardocr_url,
					IdentityYituService.class.getSimpleName().toUpperCase(), param);
			if (StringUtils.isBlank(rmcResp.getErrorCode())) {// 请求成功并完成
				if (!StringUtils.isBlank(rmcResp.getData())) {
					YTBaseRes ytocrRes = JacksonUtil.Json2Obj(rmcResp.getData(), new TypeReference<YTBaseRes>() {
					});
					if (ytocrRes.getFacePairState() != 1000) {
						throw new IdAuthException("身份证号解析失败：" + ytocrRes.getFacePairDes());
					}
					return ytocrRes.getYTOcrResult();
				}
			}
		} catch (Exception e) {
			logger.error("IdentityYituService:idcardOcr:", e);
			throw new RMCloudRequestException(e.getMessage());
		} finally {
			if (null != ocrParam) {
				ocrParam = null;
			}
		}
		return null;
	}

	/**
	 * 调用依图活体识别接口
	 * 
	 * @param param
	 * @return
	 * @throws VituException
	 * @throws JsonParseException
	 * @throws JsonMappingException
	 * @throws IOException
	 * @throws RMCloudRequestException
	 * @throws DataException
	 */
	@Log
	public YTFacePairResult compareFacepair(FacepairParam facepairParam, String busType,int flag)
			throws IdAuthException, RMCloudRequestException {
		if (StringUtils.isBlank(facepairParam.getIdbase64()) || StringUtils.isBlank(facepairParam.getFacebase64())) {
			throw new IdAuthException("活体识别输入参数不正确");
		}
		String param = "";
		try {
			if (0 == flag) {
				param = JacksonUtil
						.Obj2Json(new YTFacepairParam(facepairParam.getIdbase64(), facepairParam.getFacebase64(), busType, "100"));
			} else {
				param = JacksonUtil
						.Obj2Json(new YTFacepairParam(facepairParam.getIdbase64(), facepairParam.getFacebase64(), busType, "200"));
			}
			RMC_BaseRespVo rmcResp = super.postRMCloudData(yitu_comparefacepair_url,
					IdentityYituService.class.getSimpleName().toUpperCase(), param);
			if (StringUtils.isBlank(rmcResp.getErrorCode())) {// 请求成功并完成
				if (!StringUtils.isBlank(rmcResp.getData())) {
					YTBaseRes ytocrRes = JacksonUtil.Json2Obj(rmcResp.getData(), new TypeReference<YTBaseRes>() {
					});
					if (ytocrRes.getFacePairState() != 2000) {
						throw new IdAuthException("活体识别失败：" + ytocrRes.getFacePairDes());
					}

					YTFacePairResult response = ytocrRes.getYTFacePairResult();
					if (0 == flag) {
						// 获取活体识别的比对结果值
						Integer liveCompareValue = (response == null)
								|| (response.getPair_verify_similarity() == null) ? 0
								: response.getPair_verify_similarity().intValue();
						if (similarityBaseline > liveCompareValue) {
							throw new IdAuthException("人脸识别失败，请再试一次");
						}
					}
					response.setPairImgs(ytocrRes.getFacebagArray());
					return response;
				}
			}
			return null;
		} catch (Exception e) {
			logger.error("IdentityYituService:compareFacepair:", e);
			throw new RMCloudRequestException(e.getMessage());
		} finally {
			if (null != facepairParam) {
				facepairParam = null;
			}
		}
	}
}
